﻿using MediatR;
using W.Product.Domain.Dto;
using W.Product.Domain.Product;
using W.Product.Read.API.Appliaction.Command.ProductTypeCommand;
using W.Product.Repository.Interface;

namespace W.Product.Read.API.Appliaction.CommHandler.ProductTypeCommandHandler
{
    public class ProductTypeSelectCommandHandler : IRequestHandler<ProductTypeSelectCommand, ProductTypePages>
    {
        private readonly IProductTypeRepository _repository;
        public ProductTypeSelectCommandHandler(IProductTypeRepository repository)
        {
            _repository = repository;
        }
        /// <summary>
        /// 显示产品类型/查询
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ProductTypePages> Handle(ProductTypeSelectCommand request, CancellationToken cancellationToken)
        {

            ProductTypePages page = new ProductTypePages();
            var menul=await _repository.GetAll();
            var list = (from a in await _repository.GetAll()
                        where a.IsDelete == false
                        select new ProductTypeDto
                        {
                            ProductTypeId=a.ProductTypeId,
                            ProductTypeNo=a.ProductTypeNo,
                            ProductTypeName =a.ProductTypeName,
                            ProductSuperior =a.ProductSuperior,
                            ProductRemarks =a.ProductRemarks,
                            CreateDate=a.CreateTime,

                            ProductTypes = (from b in menul
                                           where b.ProductTypeId == Convert.ToInt64(a.ProductSuperior)
                                           select new ProductType
                                           {
                                               ProductTypeId = Convert.ToInt32(a.ProductSuperior),
                                               ProductTypeName=b.ProductTypeName
                                               
                                           }).FirstOrDefault()
                        }).ToList();

            if (!string.IsNullOrEmpty(request.ProductTypeNo))
            {
                list=list.Where(x=>x.ProductTypeNo==request.ProductTypeNo).ToList();
            }
            if (!string.IsNullOrEmpty(request.ProductTypeName)) {
                list = list.Where(x => x.ProductTypeName.Contains(x.ProductTypeName)).ToList();
            }
           
            page.tacount = list.Count;
            page.pacount=(int) Math.Ceiling(page.tacount*1.0/request.size);
            page.List = list.OrderBy(x => x.ProductTypeId).Skip((request.index - 1) * request.size).Take(request.size).ToList();

            return page;
        }
    }
}
